// pages/socket/socket.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit : 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('onload')
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
//连接socket 
  linkSocket:function() {
    let that = this
    // wx.connectSocket({
    //   url: app.globalData.wsUrl + 'websocket?' + this.data.taskId + '&' + this.data.userId,
    //   success() {
    //     console.log('连接成功')
    //     that.initEventHandle()
    //   }
    // })
  console.log('link socket')
    wx.connectSocket({
      url: 'ws://192.168.1.2:1515',
      method: 'GET',
      success: function () {
        isConnect: true
        console.log("连接成功...")
        that.initEventHandle()
      },
      fail: function () {
        isConnect: false
        console.log("连接失败...")
      
      }
    });
  },
  // 初始化socket
  initEventHandle:function() {
    let that = this
    let heartCheck = {
      timeout: 10000,
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
      },
      start: function () {
        this.timeoutObj = setTimeout(() => {
          console.log("ping");
          wx.sendSocketMessage({
            data: "ping",
            // success(){
            //  console.log("发送ping成功");
            // }
          });
          this.serverTimeoutObj = setTimeout(() => {
            wx.closeSocket();
          }, this.timeout);
        }, this.timeout);
      }
    };
    wx.onSocketMessage((res) => {
      //收到消息
      console.log(res.data)
      if (res.data == "pong") {
        heartCheck.reset().start()
        console.log('11111')
      } else {
        // 处理数据
        console.log(res.data+'222222')
      }
    })
    wx.onSocketOpen(() => {
      console.log('WebSocket连接打开')
      heartCheck.reset().start()
    })
    wx.onSocketError((res) => {
      console.log('WebSocket连接打开失败')
      this.reconnect()
    })
    wx.onSocketClose((res) => {
      console.log('WebSocket 已关闭！')
      if(that.data.limit<12){
        this.reconnect()
      }
      
    })
  },
  // 断线重连
  reconnect:function() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    console.log('limit is '+this.data.limit)
    console.log('lockReconnect is ' + this.lockReconnect)
    if (this.data.limit < 12) {
      this.timer = setTimeout(() => {
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      this.setData({
        limit: this.data.limit + 1
      })
    }
  },

  


 // open socket  成功后状态灯变绿，失败弹出消息
  startClick: function (even) {
    this.linkSocket();

    // wx.onSocketOpen(function (res) {
    //   console.log('WebSocket连接已打开！')
    // });

    // wx.onSocketError(function (res) {
    //   console.log('WebSocket连接打开失败，请检查！')
    // });
    // // 接收消息
    // wx.onSocketMessage(function (res) {
    //   console.log('收到服务器内容：' + res.data)
    // });
  },
  //发送消息，发送成功 失败做对应操作
  sendClick: function (even) {
    wx.sendSocketMessage({
      data: "web socket"
    })
  },
 
  //监听服务器，收到消息后处理 

  //关闭socket
  closeClick: function (even) {
    wx.closeSocket({
      success: function () {
        console.log("关闭成功...")
      },
      fail: function () {
        console.log("关闭失败...")
      }
    });
    wx.onSocketClose(function (res) {
      console.log("WebSocket连接已关闭")
    })
  }
})